import requests
from urllib.request import urlretrieve
import os


headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36 Edg/88.0.705.56'
}

class Music:
    def __init__(self, song="", author=[], url="", _id=0):
        self.song = song
        self.author = author
        self.url = url
        self.id = _id


class User:
    def __init__(self, cookie='', uid='', ulist=[], name=''):
        self.uid = uid
        self.cookie = cookie
        self.ulist = ulist
        self.name = name


def showMusic(musics):
    music_num = 0
    for music in musics:
        music_num += 1
        print('{}-{}-{}-'.format(music_num, music.song, music.id), end="")
        author_name = ""
        for author in music.author:
            author_name = author_name + '/' + author['name']
        author_name = list(author_name)
        author_name[0] = ""
        author_name = "".join(author_name)
        print(author_name)


def searchMusic(music_ipt):
    music_res = requests.get(
        'http://42.194.219.10:8080/search?keywords=%s' % music_ipt)
    music_json = music_res.json()
    res_songs = music_json['result']['songs']
    search_music = []
    for res_song in res_songs:
        music = Music(_id=res_song['id'], song=res_song['name'])
        authors = []
        for res_author in res_song['artists']:
            res_author = {'name': res_author['name'], 'id': res_author['id']}
            authors.append(res_author)
        music.author = authors
        search_music.append(music)
    showMusic(search_music)


def login():
    email = input('请输入邮箱: ')
    password = input('请输入密码: ')
    try:
        login_res = requests.get(
            'http://42.194.219.10:8080/login?email={0}&password={1}'.format(email, password))
        user_json = login_res.json()
        user_id = user_json['account']['id']
        user_name = user_json['profile']['nickname']
        cookie = login_res.cookies
        cookie = requests.utils.dict_from_cookiejar(cookie)
        return (user_id, cookie, user_name)
    except Exception as err:
        print('登录失败: \n{0}'.format(err))


def getUserList(user):
    getList_res = requests.get(
        'http://42.194.219.10:8080/user/playlist?uid={0}'.format(user.uid), cookies=user.cookie)
    list_json = getList_res.json()['playlist']
    userlist = []
    for i in list_json:
        list_info = {'name': i['name'], 'lid': i['id']}
        userlist.append(list_info)
    return userlist


def downloadList(uid, user):
    try:
        res = requests.get(
            'http://42.194.219.10:8080/playlist/detail?id=%s' % uid, cookies=user.cookie).json()

        # 从trackIds中获取音乐
        if res['playlist']['tracks'] != res['playlist']['trackIds']:
            listSongs = res['playlist']['trackIds']
            listSongsId = []
            for i in listSongs:
                music = Music(_id=i['id'])
                listSongsId.append(music)
            listSongsId = getSongInfo(listSongsId, user)
        # 从tracks中获取音乐
        else:
            listSongs = res['playlist']['tracks']
            listSongsId = []
            for i in listSongs:
                url = requests.get('http://42.194.219.10:8080/song/url?id=%s' % i['id'], cookies=user.cookie).json()['data'][0]['url']
                music = Music(_id=i['id'], song=i['name'],
                            url=url)
                authors = []
                for res_author in i['ar']:
                    res_author = {
                        'name': res_author['name'], 'id': res_author['id']}
                    authors.append(res_author)
                music.author = authors
                listSongsId.append(music)
        showMusic(listSongsId)
        print('Downloading...')
        listName = res['playlist']['name']
        try:
            os.mkdir(os.path.join(os.getcwd(), 'myMusic', listName))
        except:
            pass
        for i in listSongsId:
            songName = i.song+'.mp3'
            path = os.path.join(os.getcwd(), 'myMusic', listName, songName)
            if download(path, i):
                print(i.song+'下载成功...')
            else:
                print(i.song+'下载失败...')
        print('下载完成!请在当前目录查询')
    except Exception as e:
        print('操作错误，请重试')
        print(e)

def download(path, song):
    try:
        res = requests.get(song.url, headers=headers)
        with open(path, 'wb') as f:
            f.write(res.content)
        return True
    except Exception as e:
        print(e)
        return False
    


def ifFolder():
    if not os.path.exists(os.path.join(os.getcwd(), 'myMusic')):
        os.mkdir(os.path.join(os.getcwd(), 'myMusic'))

def dailySignin(user):
    requests.get('http://42.194.219.10:8080//daily_signin', cookies=user.cookie)
    print('签到成功')

def getSongInfo(songsId, user):
    ids = [str(i.id) for i in songsId]
    ids = ','.join(ids)
    songs = []
    resInfos = requests.get('http://42.194.219.10:8080/song/detail?ids=%s' % ids).json()['songs']
    for i in resInfos:
        url = requests.get('http://42.194.219.10:8080/song/url?id=%s' % i['id'], cookies=user.cookie).json()['data'][0]['url']
        music = Music(_id=i['id'], song=i['name'],
                    url=url)
        authors = []
        for res_author in i['ar']:
            res_author = {
                'name': res_author['name'], 'id': res_author['id']}
            authors.append(res_author)
        music.author = authors
        songs.append(music)
    return songs


    # return songs


def main():
    user = User()
    while True:
        print('1.Login')
        print('2.搜索音乐')
        print('3.下载音乐')
        print('4.获取用户歌单')
        print('5.下载整个歌单')
        print('6.签到')
        print('7.退出')
        music_ipt = input('< ')
        if music_ipt == '1':
            user.uid, user.cookie, user.name = login()
            print('Welcom {}:{}'.format(user.name, user.uid))

        elif music_ipt == '2':
            searchMusic(input('< '))

        elif music_ipt == '3':
            ipt = input('Song Id: ')
            url = requests.get('http://42.194.219.10:8080/song/url?id=%s' % ipt, cookies=user.cookie).json()['data'][0]['url']
            songName = input('取个名字? ')
            song = Music(song=songName, url=url, _id=ipt)
            path = os.path.join(os.getcwd(), 'myMusic', songName+'.mp3')
            if download(path, song):
                print(song.song+'下载成功!')
            else:
                print('下载失败!')



        elif music_ipt == '4':
            if user.uid != '' and user.cookie != '':
                user.ulist = getUserList(user)
                for i in user.ulist:
                    print('{}. ListName:{} Lid:{}'.format(
                        str(user.ulist.index(i)+1), i['name'], i['lid']))
            else:
                print('请先登录!')

        elif music_ipt == '5':
            if user.uid != '' and user.cookie != '':
                ifFolder()
                uid_ipt = input('请输入歌单id(uid): ').strip()
                downloadList(uid_ipt, user)
            else:
                print('请先登录!')

        elif music_ipt == '6':
            if user.uid != '' and user.cookie != '':
                dailySignin(user)
            else:
                print('请先登录!')

        elif music_ipt == '7':
            break


if __name__ == "__main__":
    main()
